<template>
    <div v-if="isCart === 1" class="handler">
        <div>
            <el-button type="success" :disabled="but" @click="refresh">洗牌</el-button>
        </div>
        <div>
            <el-button type="primary" :disabled="but" @click="handleDifficulty(3)">
                难度1
            </el-button>
            <el-button type="primary" :disabled="but" @click="handleDifficulty(4)">难度2</el-button>
            <el-button type="primary" :disabled="but" @click="handleDifficulty(5)">难度3</el-button>
            <el-button type="primary" :disabled="but" @click="handleDifficulty(6)">难度4</el-button>
        </div>
        <div>
            <el-button type="danger" @click="isCart = 3">我的卡片</el-button>
            <el-button type="info" @click="handleQuit">返回</el-button>
        </div>
        <div class="title">进行洗牌，表示卡片的中奖号改变，并且对卡片位置进行重新排列</div>
        <div class="title">不同的难度对应不同的优惠力度，难度越大，对应的优惠呈倍数增加，但中奖的概率会直线减少</div>
        <div class="title">开始你的选择吧</div>
    </div>
    <div v-if="isCart === 2" class="handler sub">
        <div>
            <el-button v-show="user.cardList.length < 3"
                       type="danger" @click="isCart = 1;">重新抽卡
            </el-button>
            <el-button type="danger" @click="isCart = 3">我的卡片</el-button>
            <el-button type="info" @click="handleQuit">返回</el-button>
        </div>
        <div v-if="price > 0" class="title">恭喜您，中奖啦！！！</div>
        <div v-else class="title">很遗憾，未能中奖</div>
    </div>
    <div v-if="isCart === 3" class="handler sub">
        <div>
            <el-button type="info" @click="handleQuit">返回</el-button>
        </div>
        <div class="title">
            一个人一个月只有3次抽奖机会，中奖全凭个人运气哦，单次中奖额度最高可达4000元，下面是您这个月已抽卡片
        </div>
    </div>
    <div v-if="isCart === 1" class="activity-box">
        <div class="cart-item" :style="{background: color}" v-for="item in childStrList" draggable="true">
            <div class="cart-item">
                <el-button size="large" type="danger" :disabled="isCart !== 1"
                           @click="handleClick(item)">点我
                </el-button>
            </div>
            <div class="cart-id">{{ item }}</div>
        </div>
    </div>
    <div v-else-if="isCart === 2" class="active-card">
        中奖金额： {{ price }}
    </div>
    <div v-else-if="isCart === 3" class="my-card">
        <div class="card-null" v-show="user.cardList.length === 0"
             @click="isCart = 1">
            第一步，抽卡
        </div>
        <div class="card-null" v-show="user.cardList.length === 0"
             @click="isCart = 1">
            第二步，中奖
        </div>
        <div class="card-null" v-show="user.cardList.length === 0"
             @click="isCart = 1">
            第三步，兑换
        </div>
        <draggable v-show="user.cardList.length > 0" class="my-card" v-model="user.cardList" :animation="300" :handle="'.mover'">
            <transition-group>
                <div class="cart-item" :style="{background: color}" v-for="item in user.cardList">
                    <div v-if="item.price > 0" class="title mover">金额： {{ item.price }}</div>
                    <div v-else class="title mover">空空如也</div>
                    <div class="but">
                        <el-button v-show="item.price > 0" type="primary" @click="handleExchange">去兑换</el-button>
                        <el-button v-show="item.price > 0" type="success" @click="handleUpgrade">去升级</el-button>
                    </div>
                </div>
            </transition-group>
        </draggable>
        <div v-if="user.cardList.length == 1" class="card-null"
             @click="isCart = 1">空位，去抽卡吧
        </div>
        <div v-if="user.cardList.length == 1 || user.cardList.length == 2" class="card-null"
             @click="isCart = 1">空位，去抽卡吧
        </div>
    </div>
</template>

<script setup lang="ts">

import {onMounted, ref} from "vue";
import router from "@/router";
import {messageConfirm, notifySuccess} from "@/utils/modal";
import {insertCard} from "@/api/card";
import {CardForm} from "@/api/card/types";
import useStore from "@/store";

const {user} = useStore();

const childStrList = ref([] as string[]);

const color = ref('#FFFFFF');

const but = ref(false);

const isCart = ref(1);

const length = ref(3);

const price = ref(0);

const str = 'luowei202059065229';

/**
 * 随机生成minLength~maxLength位数的子串(且用0补充为3位)
 */
const partition = (str: string, minLength: number, maxLength: number): string[] => {
    const substrings: string[] = [];
    let remainingLength = str.length;
    while (remainingLength >= minLength) {
        let length = minLength;
        if (remainingLength === minLength) {
            length = Math.floor(Math.random() * (maxLength - minLength + 1)) + minLength;
        } else {
            length = Math.floor(Math.random() * (Math.min(maxLength, remainingLength) - minLength + 1)) + minLength;
        }
        const substring = str.substring(0, length).padEnd(maxLength, '0');
        substrings.push(substring);
        str = str.substring(length);
        remainingLength = str.length;
    }
    if (remainingLength > 0) {
        substrings.push(str.padEnd(maxLength, '0'));
    }
    return substrings;
}

/**
 * 数组洗牌
 * @param array
 */
const shuffleArray = (array: string[]): string[] => {
    for (let i = array.length - 1; i > 0; i--) {
        const j = Math.floor(Math.random() * (i + 1));
        [array[i], array[j]] = [array[j], array[i]];
    }
    color.value = '#' + Math.floor(Math.random() * 16777215).toString(16);
    return array;
}

function pause(delay: number) {
    return new Promise((resolve) => {
        setTimeout(resolve, delay);
    });
}

const refresh = async () => {
    but.value = true;
    isCart.value = 1;
    childStrList.value = shuffleArray(partition(str, 1, length.value));
    await pause(1000).then(() => {
        but.value = false;
    });
}

/**
 * 抽奖: (length字符串长度 num字母长度)
 * 包含 length 位字母则中大奖励(500~1000)*(num-2)的金额
 * 包含 length-1 位字母则中一般奖励(100~200)*(num-2)的金额
 * 其中 结果 <= 0 均不中奖
 */
const luckyDraw = (id: string): number => {
    const regex = /[a-zA-Z]/g;
    const num = id.match(regex) ? id.match(regex)?.length : 0;
    if (num === id.length) {
        let price = Math.ceil(Math.random() * 500) + 500;
        return price * (num - 2);
    } else if (num === id.length - 1) {
        let price = Math.ceil(Math.random() * 100) + 100;
        return price * (num - 2);
    } else {
        return 0;
    }
}

const handleDifficulty = async (l: number) => {
    but.value = true;
    length.value = l;
    childStrList.value = shuffleArray(partition(str, 1, length.value));
    await pause(1000).then(() => {
        but.value = false;
    });
}

const handleQuit = () => {
    router.push({path: "/"});
}

const handleClick = (item: string) => {
    if (user.cardList.length >= 3) {
        messageConfirm("最多只能有3张卡片");
        return;
    }
    isCart.value = 2;
    let tmp = luckyDraw(item);
    price.value = tmp > 0 ? tmp : 0;
    insertCard({
        price: price.value,
    } as CardForm).then(({data}) => {
        if (data.flag) {
            notifySuccess(data.msg);
        } else {
            messageConfirm("记录失败");
        }
    });
    user.setCardList();
}

const handleUpgrade = () => {
    router.push({path: "/purchased"});
}

const handleExchange = () => {
    router.push({path: "/form"});
}

const getMyCart = () => {
    user.setCardList();
    if (user.cardList.length >= 3) {
        isCart.value = 3;
    }
}

onMounted(() => {
    refresh();
    getMyCart();
})
</script>

<style scoped lang="scss">
.handler {
  height: 180px;
  width: 100%;
  text-align: center;
  margin-top: 20px;
  display: grid;
  grid-template-columns: repeat(3, 1fr);

  .title {
    margin: 0 40px;
  }
}

.handler.sub {
  grid-template-columns: repeat(1, 1fr);
}

.activity-box {
  width: 80%;
  display: grid;
  grid-template-columns: repeat(4, 1fr);
  grid-gap: 40px;
  align-items: center;
  place-content: center;
  margin: 0 auto;
}

.cart-item {
  position: relative;
  width: 300px;
  height: 300px;
  background: rgba(250, 120, 20, .8);
  display: flex;
  justify-content: center;
  align-items: center;
  border-radius: 20px;
  border: #fd7c11 solid 1px;
  aspect-ratio: 1;
  transition: .5s;
  transition-timing-function: cubic-bezier(0.4, 0, 0.6, 1);

  &:hover {
    cursor: pointer;
    transform: perspective(2800px) rotate3d(1, 1, 1, 20deg);
    transform-origin: right;
    box-shadow: -10px 10px 10px 5px rgba(0, 0, 0, .5);
  }

  .cart-id {
    position: absolute;
    bottom: 5px;
    left: 10px;
    z-index: -1;
  }
}

.active-card {
  width: 80%;
  height: 60vh;
  text-align: center;
  margin: 0 auto;
  background: #fd7c11;
  border: #fd7c11 solid 1px;
  border-radius: 20px;
  box-shadow: 0 0 10px 5px #8c939d;
}

.my-card {
  position: relative;
  width: 80%;
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  grid-gap: 40px;
  align-items: center;
  place-content: center;
  margin: 0 auto;

  .card-null {
    text-align: center;

    &:hover {
      cursor: pointer;
      color: rgba(250, 120, 20, .5);
    }
  }

  .but {
    position: absolute;
    bottom: 10px;
  }
}
</style>